package com.csdj.t301.aop;

import com.alibaba.fastjson.JSONObject;
import com.csdj.t301.constant.CommonConstant;
import com.csdj.t301.entity.User;
import com.csdj.t301.service.ICache;
import com.csdj.t301.vo.WebResult;
import com.mysql.cj.jdbc.ha.ReplicationMySQLConnection;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * 登录核验
 * author:cloud
 * date:2021/3/20 0020
 **/
public class LoginInterceptor implements HandlerInterceptor {

    private Logger log = Logger.getLogger("LoginInterceptor");

    //redis服务
    @Resource
    private ICache cache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

//        boolean isLogin = false;

        //从请求头中取出token和userid nginx默认会过滤掉下划线的头信息
        String token = request.getHeader(CommonConstant.HEAD_TOKEN);
        String userIdStr = request.getHeader(CommonConstant.HEAD_USERID);
        if(StringUtils.isEmpty(token) || StringUtils.isEmpty(userIdStr)){
            //用户没有登录
        }else{
            //从redis中取出用户的token
            String cacheToken = cache.get(CommonConstant.CACHE_TOKEN_PREFIX+userIdStr);
            if(StringUtils.isNotEmpty(cacheToken)){
                if(cacheToken.equals(token)){
                    //用户已经登录
                    return true;
                }
            }
        }

        //返回统一格式的数据
        WebResult result = new WebResult(401);
        result.setMsg("没有登录");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.write(JSONObject.toJSONString(result));
        out.flush();
        out.close();
        //拦截请求， 停止调用handler
        return false;



        //从session中取数据
//        User user = (User)request.getSession().getAttribute("user");
        //判断 user是否为空， 如果是空则没有登录 ，
//        if(user == null){
//            log.info("用户没有登录");
//            log.debug("debg");
//            log.error("error");
//            //返回统一格式的数据
//            WebResult result = new WebResult(401);
//            result.setMsg("没有登录");
//            response.setContentType("text/html;charset=utf-8");
//            PrintWriter out = response.getWriter();
//            out.write(JSONObject.toJSONString(result));
//            out.flush();
//            out.close();
//            //拦截请求， 停止调用handler
//            return false;
//        }else{
//            //放行，调用handler
//            return true;
//        }
    }
}
